import axios from "axios";
import { ElMessage } from "element-plus";

const request = axios.create({
  baseURL: "https:/v3pz.itndedu.com/v3pz",
  timeout: 5000,
});

request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("pz_token");
    //不需要携带token的api
    const whiteList = ["/get/code", "/user/authentication", "/login"];
    if (!whiteList.includes(config.url) && token) {
      config.headers["x-token"] = token;
    }
    return config; // 必须返回config,不要漏掉!!!!!
  },
  (error) => Promise.reject(error)
);

request.interceptors.response.use(
  (response) => {
    //对接口异常的数据,给用户提示
    if (response.data.code === -1) {
      ElMessage.warning(response.data.message);
    }
    if (response.data.code === -2) {
      localStorage.removeItem("pz_token");
      localStorage.removeItem("pz_userInfo");
      window.location.href = "/login";
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default request;
